package com.huaxin.hxcloud.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.RepairTaskDetailDTO;
import com.huaxin.common.Entity.TaskMaterial;
import com.huaxin.common.Entity.TaskWarning;
import com.huaxin.common.Entity.WorkTask;
import com.huaxin.common.media.ImageGalleryActivity;
import com.huaxin.common.media.view.PhotoAddView;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.Log;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.SDKBug;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.utils.Util;
import com.huaxin.common.view.AmountView;
import com.huaxin.hxcloud.Adapter.HxMedicineAdapter;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.dialog.HxSPTWritePartsDialog;
import com.huaxin.hxcloud.dialog.HxSpstroCauseDlogFragment;
import com.huaxin.hxcloud.eventBus.HxSpttroCauseEventBus;
import com.huaxindata.common.util.HxLogUtils;
import com.huaxindata.im.main.manager.UserManager;
import com.luck.picture.lib.PictureSelector;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Administrator on 2016/9/28.
 */
public class RepairTaskDetailActivity extends BaseActivity {


    WarningAdapter warningAdapter;
    ToolAdapter    toolAdapter;
    //    @BindView(R.id.tv_title)
    //    TextView         tvTitle;
    @BindView(R.id.tv_station_area)
    TextView         tv_station_area;
    @BindView(R.id.tv_station_state)
    TextView         tv_station_state;
    @BindView(R.id.tv_station_name)
    TextView         tvStationName;
    @BindView(R.id.more)
    ImageView        more;
    @BindView(R.id.toolbar)
    Toolbar          toolbar;
    @BindView(R.id.tv_des)
    TextView         tvDes;
    @BindView(R.id.warning_list)
    RecyclerView     warningList;
    @BindView(R.id.desEdit)
    EditText         desEdit;
    @BindView(R.id.photo_grid)
    PhotoAddView     photoGrid;
    @BindView(R.id.ll_edit)
    LinearLayout     llEdit;
    @BindView(R.id.tv_remark)
    TextView         tvRemark;
    @BindView(R.id.ls_img)
    RecyclerView     lsImg;
    @BindView(R.id.ll_text)
    LinearLayout     llText;
    @BindView(R.id.ll_result)
    LinearLayout     llResult;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.mark)
    View             mark;
    @BindView(R.id.tool_list)
    RecyclerView     toolList;
    @BindView(R.id.commit)
    Button           commit;
    @BindView(R.id.bottom_layout)
    LinearLayout     bottomLayout;
    @BindView(R.id.toolbox)
    ImageView        toolbox;
    @BindView(R.id.content)
    FrameLayout      content;
    @BindView(R.id.parts_tv)
    TextView         pratsTv;
    @BindView(R.id.finish_task_btn)
    Button           mFinishTaskBtn;
    @BindView(R.id.type_des)
    TextView         mTypeDesTv;
    @BindView(R.id.ll_drug)
    LinearLayout     ll_drug;
    @BindView(R.id.medicine_recycler)
    RecyclerView     mMedicineRcycler;
    @BindView(R.id.medicine_des_tv)
    TextView         mMdicineDesTv;
    @BindView(R.id.trouble_cause_rv)
    RelativeLayout   mTroubleCauseRv;
    @BindView(R.id.describe_tv)
    TextView         mDescribeTv;
    @BindView(R.id.device_name_tv)
    TextView         devieceNameTv;
    private int    workTaskId;
    private String stationCode;
    private int    taskType;
    private int    workTaskState;
    private String title;
    private List<TaskMaterial> toolData = new ArrayList<>();
    private List               warnData = new ArrayList<>();
    private ProgressDialog waitDialog;
    private String         stationName;
    private String         taskDes;
    private ImgAdapter     imgAdapter;
    private List<String> imgData = new ArrayList<>();
    private String                    taskRemark;
    private HxMedicineAdapter         mHxMedicineAdapter;
    private String                    mDesEd;
    private List<MultipartBody.Part>  mImgFileParts;
    private HxSpstroCauseDlogFragment mTroubleCauseDialogFragment;
    private String                    mFlagTitle;
    private Gson                      mGson;
    private String                    mSelectCauseDTO;
    //站点巡检单状态:0、未派工;1、已派工;2、处理中; 3已完成
    private final int WORK_TASK_TYPE_NOT    = 1;
    private final int WORK_TASK_TYPE_START  = 2;
    private final int WORK_TASK_TYPE_FINISH = 3;
    private RepairTaskDetailDTO.Data mRepairTaskDetailDTOData;


    public static void start(Activity context, WorkTask workTask) {
        Intent intent = new Intent(context, RepairTaskDetailActivity.class);
        intent.putExtra(Constants.IK_WT_ID, workTask.getId());
        intent.putExtra(Constants.IK_STATION_CODE, workTask.getStationCode());
        intent.putExtra(Constants.IK_STATION_NAME, workTask.getStationName());
        intent.putExtra(Constants.IK_WT_TYPE, workTask.getTaskType());
        intent.putExtra(Constants.IK_WT_TITLE, workTask.getTitle());
        intent.putExtra(Constants.IK_WT_STATE, workTask.getWorkTaskState());
        context.startActivityForResult(intent, Constants.RET_WT_STATE);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_WT_ID)) {
            workTaskId = extras.getInt(Constants.IK_WT_ID);
            stationCode = extras.getString(Constants.IK_STATION_CODE);
            stationName = extras.getString(Constants.IK_STATION_NAME);
            taskType = extras.getInt(Constants.IK_WT_TYPE);
            title = extras.getString(Constants.IK_WT_TITLE);
            workTaskState = extras.getInt(Constants.IK_WT_STATE);
        } else {
            finish();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_worktask_detail;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void requestData() {
        apiRequestData(LOADING);
    }

    private void apiRequestData(int status) {
        updateLoadStatus(status);
        Call<RepairTaskDetailDTO> call = HxTransmitRequestHelper.getRequestApi().getRepairTaskDetail(workTaskId,
                stationCode, taskType);
        autoClose(call);
        call.enqueue(new Callback<RepairTaskDetailDTO>() {
            @Override
            public void onResponse(Call<RepairTaskDetailDTO> call, Response<RepairTaskDetailDTO>
                    response) {
                RepairTaskDetailDTO repairTaskDetailDTO = response.body();
                if (response.isSuccessful()) {
                    if (repairTaskDetailDTO != null && repairTaskDetailDTO.isSuccessful()) {
                        updateLoadStatus(LOAD_SUCCESS);
                        toolData.clear();
                        warnData.clear();
                        imgData.clear();
                        mRepairTaskDetailDTOData = repairTaskDetailDTO.getData();
                        toolData.addAll(mRepairTaskDetailDTOData.getMaterialInfos());
                        List<TaskWarning> datas = mRepairTaskDetailDTOData.getWarningInfos();
                        if (datas != null) {
                            warnData.addAll(datas);
                        }
                        List<String> idatas = mRepairTaskDetailDTOData.getPictureInfos();

                        if (idatas != null) {
                            imgData.addAll(idatas);
                        }
                        //TODO 视频提前下载
                        taskRemark = repairTaskDetailDTO.getWorkTaskResolvent();
                        taskDes = repairTaskDetailDTO.getWorkTaskDescription();
                        warningAdapter.handleExtraView();
                        warningAdapter.notifyDataSetChanged();
                        toolAdapter.notifyDataSetChanged();
                        //药剂类型 避免空指针报错
                        mHxMedicineAdapter.setNewData(mRepairTaskDetailDTOData.getMedicineTypeSel());
                        //故障原因
                        mTroubleCauseDialogFragment = HxSpstroCauseDlogFragment.newInstance(mRepairTaskDetailDTOData.getMalfunctionReason(), workTaskState);
                        //设备
                        if (Util.checkNull(repairTaskDetailDTO.getDeviceName())) {
                            loadTextColon(devieceNameTv, "设备", "未指定");
                        } else {
                            loadTextColon(devieceNameTv, "设备", repairTaskDetailDTO.getDeviceName());
                        }
                        //TODO head 区域 状态设置
                        tv_station_area.setText(("区域：" + repairTaskDetailDTO.getStationArea()));
                        switchStationState(repairTaskDetailDTO.getStationState());
                        mHxMedicineAdapter.setWorkTaskState(repairTaskDetailDTO.getWorkTaskState());
                        updateView();
                    } else {
                        updateLoadStatus(LOAD_ERROR);
                    }
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<RepairTaskDetailDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });

    }

    String flagSataionState = null;

    /**
     * 站点状态
     *
     * @param stationState type
     */
    private void switchStationState(int stationState) {

        switch (stationState) {
            case 0:
                flagSataionState = "正常";
                break;
            case 1:
                flagSataionState = "超时";
                break;
            case 2:
                flagSataionState = "故障";
                break;
            case 3:
                flagSataionState = "建设中";
                break;
            default:
                flagSataionState = "未知";
                break;
        }
        tv_station_state.setText(("状态：" + flagSataionState));
    }

    @Override
    public void initView() {
        tvStationName.setText(UserManager.getOrgName());
        if (waitDialog == null) {
            waitDialog = DialogUtil.getWaitDialog(this, "提交中...");
        }
        mGson = new Gson();
        setSupportActionBar(toolbar);
        //spt工作流
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            toolbox.setVisibility(View.GONE);
            pratsTv.setVisibility(View.INVISIBLE);
        } else {
            toolbox.setVisibility(View.VISIBLE);
            pratsTv.setVisibility(View.VISIBLE);
        }
        mFlagTitle = null;
        switch (taskType) {
            case 0:
                mFlagTitle = "巡检单";
                break;
            case 1:
                mFlagTitle = "排泥单";
                break;
            case 2:
                mFlagTitle = "维修单";
                break;
            case 5:
                mFlagTitle = "保养单";
                break;
            case 6:
                mFlagTitle = "加药单";
                break;
            default:
                mFlagTitle = "维修单";
                break;
        }
        toolbar.setTitle(mFlagTitle);
        warningAdapter = new WarningAdapter();
        warningList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        warningList.setAdapter(warningAdapter);

        toolAdapter = new ToolAdapter();
        toolList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        toolList.setAdapter(toolAdapter);

        imgAdapter = new ImgAdapter();
        toolList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        lsImg.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        lsImg.setAdapter(imgAdapter);
        //spt 力鼎上传视频
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode()) || Constant.LDOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            photoGrid.isRecorderVideo(true);
        } else {
            photoGrid.isRecorderVideo(false);
        }
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            initSpecialView();
        }
    }

    /**
     * 加药类型
     */
    private final int TYPE_MDICINE = 6;

    //维修单类型
    private final int TYPE_MAINTAIN = 2;

    /**
     * 特殊类型 根据 taskType判断
     */
    private void initSpecialView() {
        mHxMedicineAdapter = new HxMedicineAdapter();
        mHxMedicineAdapter.setWorkTaskState(workTaskState);
        switch (taskType) {
            //只有维修单才有故障原因 选择
            case TYPE_MAINTAIN:
                mFinishTaskBtn.setVisibility(View.VISIBLE);
                bottomLayout.setVisibility(View.GONE);
                mDescribeTv.setText("记录");
                mTroubleCauseRv.setVisibility(View.VISIBLE);
                break;
            case TYPE_MDICINE:
                mFinishTaskBtn.setVisibility(View.VISIBLE);
                bottomLayout.setVisibility(View.GONE);
                mMdicineDesTv.setVisibility(View.VISIBLE);
                mMedicineRcycler.setVisibility(View.VISIBLE);
                ll_drug.setVisibility(View.VISIBLE);
                mDescribeTv.setText("记录");
                mMedicineRcycler.setLayoutManager(new LinearLayoutManager(this));
                mMedicineRcycler.setAdapter(mHxMedicineAdapter);
                //NestedScrollView嵌套RecyclerView时,每次打开界面都是定位在RecyclerView在屏幕顶端,列表上面的布局都被顶上去了.
                mMedicineRcycler.setFocusableInTouchMode(false);
                break;
            default:
                break;
        }
    }

    public void updateView() {
        //        tvTitle.setText(title);
        //        loadText(tvTitle, title, "工单未填标题");

        loadText(tvRemark, taskRemark, "无描述信息");
        //   loadText(tvDes, "描述：" + taskDes, "描述：暂无");
        if (Util.checkNull(taskDes)) {
            loadTextColon(tvDes, "描述", "暂无");
        } else {
            loadTextColon(tvDes, "描述", taskDes);
        }
        //站点巡检单状态:0、未派工;1、已派工;2、处理中; 3已完成
        switch (workTaskState) {
            case WORK_TASK_TYPE_NOT:
                commit.setText("开始任务");
                mFinishTaskBtn.setText("开始任务");
                llResult.setVisibility(View.GONE);
                llEdit.setVisibility(View.GONE);
                llText.setVisibility(View.GONE);
                break;
            case WORK_TASK_TYPE_START:
                mFinishTaskBtn.setText("完成任务");
                commit.setText("完成任务");
                SDKBug.setBackgroundResourceWithPadding(commit, R.drawable.bg_bt_blue);
                SDKBug.setBackgroundResourceWithPadding(mFinishTaskBtn, R.drawable.bg_bt_blue);
                llResult.setVisibility(View.VISIBLE);
                llEdit.setVisibility(View.VISIBLE);
                llText.setVisibility(View.GONE);
                break;
            case WORK_TASK_TYPE_FINISH:
                commit.setText("已完成");
                mFinishTaskBtn.setText("已完成");
                SDKBug.setBackgroundResourceWithPadding(commit, R.drawable.bg_bt_gray);
                SDKBug.setBackgroundResourceWithPadding(mFinishTaskBtn, R.drawable.bg_bt_gray);
                llResult.setVisibility(View.VISIBLE);
                llEdit.setVisibility(View.GONE);
                llText.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }


    @OnClick({R.id.toolbox, R.id.commit, R.id.mark, R.id.finish_task_btn, R.id.trouble_cause_rv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.commit:
                //站点巡检单状态:0、未派工;1、已派工;2、处理中; 3已完成
                switch (workTaskState) {
                    case WORK_TASK_TYPE_NOT:
                        apiAcceptRepairTask();
                        break;
                    case WORK_TASK_TYPE_START:
                        HxSPTWritePartsDialog writePartsDialog = HxSPTWritePartsDialog.newInstance();
                        writePartsDialog.show(getFragmentManager(), "write_parts");
                        writePartsDialog.setOnWritePatsClickListener(new HxSPTWritePartsDialog.OnWritePatsClickListener() {
                            @Override
                            public void content(String content) {
                                setWriteParts(content);
                            }
                        });
                        break;
                    case WORK_TASK_TYPE_FINISH:
                        break;
                    default:
                        break;
                }

                break;
            case R.id.toolbox:
            case R.id.mark:
                if (toolData.isEmpty()) {
                    ToastUtil.showToast("未携带配件");
                    return;
                }
                mark.setVisibility(toolList.getVisibility() == View.VISIBLE ? View.GONE : View
                        .VISIBLE);
                toolList.setVisibility(toolList.getVisibility() == View.VISIBLE ? View.GONE :
                        View.VISIBLE);
                break;
            //加药完成任务
            case R.id.finish_task_btn:
                finishTasd();
                break;
            case R.id.trouble_cause_rv:
                switch (workTaskState) {
                    case WORK_TASK_TYPE_NOT:
                        ToastUtil.showToast("先开启任务单");
                        break;
                    case WORK_TASK_TYPE_START:
                    case WORK_TASK_TYPE_FINISH:
                        mTroubleCauseDialogFragment.show(getFragmentManager(), "truble_cause");
                        break;
                    default:
                        break;

                }
                break;
            default:
                break;
        }
    }

    /**
     * 完成任务单
     */
    private void finishTasd() {
        switch (workTaskState) {
            case WORK_TASK_TYPE_NOT:
                apiAcceptRepairTask();
                break;
            case WORK_TASK_TYPE_START:
                switch (taskType) {
                    case TYPE_MDICINE:
                        setAddMedicine();
                        break;
                    case TYPE_MAINTAIN:
                        setPutMuddy();
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }

    /**
     * 提交维修单
     */
    private void setPutMuddy() {
        //如果用户未修改选择故障原因状态
        if (TextUtils.isEmpty(mSelectCauseDTO)) {
            mSelectCauseDTO = mGson.toJson(mRepairTaskDetailDTOData.getMalfunctionReason());
        }
        apiCommitRepairWorkTask(mSelectCauseDTO, "");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void spttroCauseEventBusEvent(HxSpttroCauseEventBus event) {
        List<RepairTaskDetailDTO.Data.malfunctionReason> hxSpttroCauseDTO = event.getHxSpttroCauseDTO();
        mSelectCauseDTO = mGson.toJson(hxSpttroCauseDTO);
        HxLogUtils.d("--故障原因111--> " + mSelectCauseDTO);
    }

    /**
     * 加药单提交
     */
    private void setAddMedicine() {
        String toJson = mGson.toJson(mHxMedicineAdapter.getData());
        HxLogUtils.d("--加药类型药量--" + toJson);
        apiCommitRepairWorkTask("", toJson);
    }

    private void setWriteParts(String content) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().getWorkTaskParts(workTaskId, content);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                ToastUtil.showToast(baseDTO.getMsg());
                apiCommitMaterial();
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                HxLogUtils.d("-onFailure--上传配件---");
            }
        });
    }


    protected class ImgAdapter extends RecyclerView.Adapter {
        private static final int ITEM_TYPE_EMPTY   = 0x02;
        private static final int ITEM_TYPE_IMG     = 0x01;
        private static final int ITEM_TYPE_DEFAULT = 0x00;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == ITEM_TYPE_IMG) {
                return new ImgHolder(mInflater.inflate(R.layout.item_h_image, parent, false));
            } else if (viewType == ITEM_TYPE_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty3, parent, false));
            }
            return null;

        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == ITEM_TYPE_IMG) {
                ((ImgHolder) holder).update(position);
            } else if (getItemViewType(position) == ITEM_TYPE_EMPTY) {
                ((EmptyHolder) holder).update(position);
            }

        }

        @Override
        public int getItemViewType(int position) {
            Object data = imgData.get(position);
            if (data.equals(Constants.EMPTY_VIEW)) {
                return ITEM_TYPE_EMPTY;
            }
            return ITEM_TYPE_IMG;
        }

        @Override
        public int getItemCount() {
            return imgData == null ? 0 : imgData.size();
        }


        public class ImgHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            @BindView(R.id.iv_img)
            ImageView ivImg;
            @BindView(R.id.play)
            ImageView paly;
            View itemView;
            int  position;

            public ImgHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
            }

            public void update(int position) {
                this.position = position;
                Log.i("lwjing", "imgpath=" + addHost(imgData.get(position)));
                if (imgData.get(position).contains(".mp4")) {
                    paly.setVisibility(View.VISIBLE);
                } else {
                    paly.setVisibility(View.GONE);
                }
                loadNetImg(ivImg, addHost(imgData.get(position)));
                itemView.setOnClickListener(this);
                paly.setOnClickListener(this);
            }


            @Override
            public void onClick(View v) {
                if (imgData.get(position).contains(".mp4")) {
                    ToastUtil.showToast("视频下载中，请稍等...");
                    PictureSelector.create(RepairTaskDetailActivity.this).externalPictureVideo(addHost(imgData.get(position)));
                } else {
                    ImageGalleryActivity.show(RepairTaskDetailActivity.this, addHost(getUrls()),
                            position, false);
                }
            }

            private String[] getUrls() {
                return imgData.toArray(new String[imgData.size()]);
            }
        }

        public class EmptyHolder extends RecyclerView.ViewHolder {
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
            }

            public void update(int position) {

            }
        }
    }

    public class ToolAdapter extends RecyclerView.Adapter<ToolAdapter.MyViewHolder> {


        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(mInflater.inflate(R.layout.item_worktask_tool, parent, false));
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.update(position);
        }

        @Override
        public int getItemCount() {
            return toolData == null ? 0 : toolData.size();
        }


        protected class MyViewHolder extends RecyclerView.ViewHolder implements AmountView
                .OnAmountChangeListener {

            @BindView(R.id.name)
            TextView   name;
            @BindView(R.id.left)
            TextView   left;
            @BindView(R.id.amount_view)
            AmountView amountView;
            private int position;

            public MyViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }


            public void update(int position) {
                this.position = position;
                TaskMaterial data = toolData.get(position);
                loadText(name, data.getMaterialName());
                loadText(left, String.valueOf(data.getRestNum()));
                amountView.setGoods_storage(data.getRestNum());
                amountView.setAmount(data.getUsedNum());
                amountView.setOnAmountChangeListener(this);
            }

            @Override
            public void onAmountChange(View view, int amount) {
                TaskMaterial data = toolData.get(position);
                data.setUsedNum(amount);
            }
        }
    }

    public class WarningAdapter extends RecyclerView.Adapter {

        private static final int TYPE_EMPTY = 0x00;
        private static final int TYPE_ITEM  = 0x01;

        /**
         * add before notifyDataSetChanged!
         */
        public void handleExtraView() {
            int length = warnData.size();
            for (int i = 0; i < length; i++) {
                if (getItemViewType(i) != TYPE_ITEM) {
                    warnData.remove(i);
                    i--;
                    length--;
                }
            }
            if (warnData.isEmpty()) {
                warnData.add(Constants.EMPTY_VIEW);
            }
        }

        @Override
        public int getItemViewType(int position) {
            if (warnData.get(position) instanceof TaskWarning) {
                return TYPE_ITEM;
            } else if (warnData.get(position) instanceof String) {
                return TYPE_EMPTY;
            }
            return 0;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_tip, parent,
                        false));
            } else if (viewType == TYPE_ITEM) {
                return new WarningHolder(mInflater.inflate(R.layout.item_worktask_warning,
                        parent, false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            if (getItemViewType(position) == TYPE_EMPTY) {
                ((EmptyHolder) holder).update(position);
            } else if (getItemViewType(position) == TYPE_ITEM) {
                ((WarningHolder) holder).update(position);
            }
        }


        @Override
        public int getItemCount() {
            return warnData == null ? 0 : warnData.size();
        }

        public class EmptyHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_tip)
            TextView tvTip;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }

            public void update(int position) {
                tvTip.setText("未绑定告警");
            }
        }

        public class WarningHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.value)
            TextView value;
            @BindView(R.id.name)
            TextView name;
            @BindView(R.id.date)
            TextView date;

            public WarningHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }


            public void update(int position) {
                TaskWarning data = (TaskWarning) warnData.get(position);
                loadText(value, data.getDescription(), "暂无");
                loadText(name, data.getTitle());
                loadText(date, dateFormat(data.getCreateDate()));
            }

        }
    }


    public void apiCommitMaterial() {
        JsonArray ja = new JsonArray();
        for (TaskMaterial material : toolData) {
            JsonObject mjo = new JsonObject();
            mjo.addProperty("materialId", material.getMaterialId());
            mjo.addProperty("materialName", material.getMaterialName());
            mjo.addProperty("restNum", material.getRestNum());
            mjo.addProperty("usedNum", material.getUsedNum());
            ja.add(mjo);
        }
        waitDialog = DialogUtil.getWaitDialog(this, "提交中...");

        waitDialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().commitMaterial(workTaskId, ja.toString());
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        apiCommitRepairWorkTask("", "");
                    } else {
                        waitDialog.dismiss();
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    waitDialog.dismiss();
                    ToastUtil.showToast("数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                waitDialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });

    }

    /**
     * 完成任务单接口
     * 如果上传的参数没有就传null
     *
     * @param malfunctionReason 故障原因
     * @param medicineTypeSel   加药类型及相对应的药量
     */

    private void apiCommitRepairWorkTask(String malfunctionReason, String medicineTypeSel) {
        //描述
        mDesEd = desEdit.getText().toString().trim();
        //上传图片路径
        mImgFileParts = RequestHelper.createFileParts(photoGrid.getCompressPaths());
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().commitRepairWorkTask(workTaskId, stationCode,
                mDesEd, mImgFileParts, malfunctionReason, medicineTypeSel);
        for (int i = 0; i < mImgFileParts.size(); i++) {
        }
        HxLogUtils.d("--完成接口-->" + "--图片路径--" + mImgFileParts + " --描述-->" + mDesEd + " --加药json数据-->" + medicineTypeSel + " --故障原因-->" + malfunctionReason);
        waitDialog.show();
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                waitDialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        ToastUtil.showToast("提交成功");
                        workTaskState = 3;
                        requestData();
                        //                        updateView();
                        setResult();
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                waitDialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });
    }

    private void setResult() {
        Intent intent = new Intent();
        intent.putExtra(Constants.IK_WT_STATE, workTaskState);
        setResult(RESULT_OK, intent);
        finish();
    }

    public void apiAcceptRepairTask() {
        waitDialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().acceptWorkTask(workTaskId);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                waitDialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        ToastUtil.showToast("开启成功");
                        workTaskState = 2;
                        apiRequestData(LOAD_SUCCESS);
                        // updateView();
                        //   setResult();
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                waitDialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });
    }
}